package com.javalearn;

import java.text.SimpleDateFormat;
import java.util.Date;

public class SynchronizeTest {
	public synchronized void normaltest1() {
		System.out.println("start normaltest1....."+currentTime());
		sleepSeconds(5);
		System.out.println("end normaltest1....."+currentTime());
	}
	public synchronized void normaltest2() {
		System.out.println("start normaltest2....."+currentTime());
		sleepSeconds(5);
		System.out.println("end normaltest2....."+currentTime());
	}
	
	public synchronized static void staticTest1() {
		System.out.println("start staticTest1....."+currentTime());
		sleepSeconds(5);
		System.out.println("end staticTest1....."+currentTime());
	}
	public synchronized static void staticTest2() {
		System.out.println("start staticTest2....."+currentTime());
		sleepSeconds(5);
		System.out.println("end staticTest2....."+currentTime());
	}
	
	public void blockTest1() {
		System.out.println("start blockTest1....."+currentTime());
		synchronized(this) {
			sleepSeconds(5);
		}
		System.out.println("end blockTest1....."+currentTime());
	}
	public void blockTest2() {
		System.out.println("start blockTest2....."+currentTime());
		synchronized(this) {
			sleepSeconds(5);
		}
		System.out.println("end blockTest2....."+currentTime());
	}
	
	public  static void sleepSeconds(int time) {
		try {
			Thread.sleep(time*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public static String currentTime() {
		Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date.getTime());
        return time;
		
	}
	public static void main(String[] args) {
		//1.普通方法块，锁normalst对象
		final SynchronizeTest normalst = new SynchronizeTest();
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				normalst.normaltest1();
			}
		});
		
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				normalst.normaltest2();
			}
		});
		t1.start();
		t2.start();
		
		//2.静态方法块，锁SynchronizeTest类对象
		final SynchronizeTest staticst1 = new SynchronizeTest();
		final SynchronizeTest staticst2 = new SynchronizeTest();
		Thread t3 = new Thread(new Runnable() {
			public void run() {
				staticst1.staticTest1();
			}
		});
		
		Thread t4 = new Thread(new Runnable() {
			public void run() {
				staticst2.staticTest2();
			}
		});
		t3.start();
		t4.start();
		
		//3.代码块，锁代码块上的对象
		final SynchronizeTest blockst = new SynchronizeTest();
		Thread t5 = new Thread(new Runnable() {
			public void run() {
				blockst.blockTest1();
			}
		});
		Thread t6 = new Thread(new Runnable() {
			public void run() {
				blockst.blockTest2();
			}
		});
		t5.start();
		t6.start();
	}
}
